<?php

	include_once("./db.php"); 
	
	$userId = $_SESSION["user"]["Id"];
	
	$ar_elements = $_REQUEST["elements"];
	
	$elements = implode($ar_elements, ",");
	
	$count = count($ar_elements);
	
	//TODO:Use some array disctinct function
	//if($ar_elements[0] == $ar_elements[1])
	//	$count--;
	
	$elementId = db_scalar("
	
	SELECT ProductId, COUNT(1) foundElements, Id
FROM (

SELECT DISTINCT ProductId, ci.ElementId, ci.Id
FROM Combination c, CombinationItem ci, TagElement te, TagUser tu, Element e
WHERE c.Id = ci.CombinationId
AND ci.ElementId
IN ( $elements ) 
AND e.Id = c.ProductId
AND e.Enabled 
AND ci.ElementId
AND tu.UserId = $userId
AND tu.TagId = te.TagId
AND c.ProductId = te.ElementId
ORDER BY c.CreateDate ASC
) t
GROUP BY ProductId
HAVING foundElements = $count
LIMIT 1");
		
	$res["sucess"] = false;
	
	if($elementId > 0)
	{
		$res["sucess"] = true;
	
		db_insert("UserElement", array(
			"UserElementUserId" => $userId,
			"UserElementElementId" => $elementId
		));
	
		$res["Elements"][] = db_row("Element", $elementId);
	}
	
	echo json_result_encode($res);

?>

